package com.tiny.core.common;

import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by gnauhsil on 2018/6/15.
 */

@Component("dataSwitch")
public class DataSwitch  extends HashMap implements Serializable {

    private Map<String, Object> dataMap = new HashMap<String, Object>();

    /**
     * 将对象转换成 Map
     * @param obj 对象类
     * @return
     */
    public Map<String,Object> setObjToMap(Object obj){
        Class c;
        try {
            c = Class.forName(obj.getClass().getName());
            Method[] methods = c.getMethods();
            for(int i=0,l=methods.length;i<l;i++){
                String method = methods[i].getName();
                System.out.println("The method is:" + method);
                if(method.startsWith("get")){
                    Object value = methods[i].invoke(obj);
                    if(value != null){
                        if(value.getClass().getClassLoader() != null){  //处理自定义的对象类型
                            setObjToMap(value);
                        }
                        String key = method.substring(3);
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                       /* if("java.util.Date".equals(value.getClass().getName())){
                            value = DateUtil.dateToString((Date)value);
                        }*/
                        System.out.println("key, value" + key + " --  " +value);
                        dataMap.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataMap;
    }

}
